﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace LKVMLMLib
{
    public partial class DuAnDaCapEntities : DbContext
    {
        public DuAnDaCapEntities(string connection_string)
            : base(connection_string)                 
        {           
        }
        public static DuAnDaCapEntities initDuAnDaCapEntities(string domain)
        {
            using (var db = new CompanyEntities())
            {          
                string connection_string= db.Licences.Where(w=>w.Domain==domain).Select(w=>w.DatabaseConectionString).SingleOrDefault();
                if (connection_string == null)
                    throw new Exception(String.Format("There is not connection string for {0}", domain));
                return new DuAnDaCapEntities(connection_string);                
            }           
        }
        public static string getDomain()
        {
            string connection = "";
            try
            {
                OperationContext operationContext = OperationContext.Current;
                HttpRequestMessageProperty httpRequest = operationContext.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                if (httpRequest != null)
                {
                    Uri viaUri = operationContext.IncomingMessageProperties.Via;
                    string host = httpRequest.Headers[System.Net.HttpRequestHeader.Host];
                    var uriBuilder = new UriBuilder(viaUri) { Host = host };
                    if (uriBuilder.Host.IndexOf("localhost") > 0)
                        connection = "localhost";
                    else
                        connection = uriBuilder.Uri.Host;
                }
            }

            catch
            {
                connection = HttpContext.Current.Request.Url.Host;
             
            }
            return connection;
        }
    }
}
   
    
   